//
//  JPOAuthViewController.swift
//  JPWeibo
//
//  Created by 哇咔咔 on 16/9/21.
//  Copyright © 2016年 jp. All rights reserved.
//

import UIKit
import SVProgressHUD

//  第三方登录视图控制器
//  新浪开发平台提供的APPKey
let WeiboAppKey = "1959555473"
//AppSecret
let WeiboAppSecret = "31f24aff1d523e23d3dce3cd8d2ffaf4"

//  授权回调页
let WeiboRedirect_Uri = "http://www.itcast.cn"

class JPOAuthViewController: UIViewController {
    
    //  MARK: -- 懒加载
    private lazy var webView: UIWebView = UIWebView()
    
    //  重写loadView, 目的把webView作为视图控制器的view
    override func loadView() {
        
        //  解决底部webView黑条
        //  改成透明解决黑条问题
        webView.isOpaque = false
        webView.delegate = self
        
        view = webView
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        requestLogin()
        setupNavUI()
    }
    
    //  请求第三方登录
    private func requestLogin() {
        //  准备url地址
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
        print(url)
        //  创建urlrequest对象
        let urlRequest = URLRequest(url: URL(string: url)!)
        
        webView.loadRequest(urlRequest)
    }
    
    //  设置导航栏按钮
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillAction))
        title = "微博"
    }
    
    //  MARK: -- 点击事件处理
    @objc private func cancelAction() {
        
        SVProgressHUD.dismiss()
        
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func autoFillAction() {
        
        print("自动填充")
    
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '865246046@qq.com';document.getElementById('passwd').value = 'fusanxiao123'")
    }
        
        
}

extension JPOAuthViewController: UIWebViewDelegate {
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print(request.url?.absoluteString)
        guard let url = request.url else {
            print("url为空")
            return false
        }
        
        //过滤不符合要求的url
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri) {
            return true
        }
        
        let query = request.url!.query
        if query!.hasPrefix("code") {
            
            guard let code = query?.substring(from: "code=".endIndex) else {
                return false
            }
            
            JPUserInfoViewModel.sharedUserInfoViewModel.requestAccessToken(code: code, callBack: { (isSuccess) in
                
                if isSuccess {
                    
                    self.dismiss(animated: false, completion: {
                        
                        NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotification), object: self)
                    })
                }
            })
        }
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        
        SVProgressHUD.dismiss()
    }
}






